package cn.datawin.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;


@Service
public class RuleService extends BaseService{
	
	public void insertRule(String rule) {
		Map map =(Map)deserialize(rule);
		String col="rule";
		this.insert(col, map);
	}
	
	public String findRule(String taskid,String pid){
		String col="rule";
		DBObject query = new BasicDBObject();
		query.put("taskid", taskid);
		if (pid !=null && !pid.equals("")) {
			query.put("pid", pid);
		}
		List<DBObject> task = this.findList(col, query);
		return serialize(task);
	}
	
	public String findRuleByid(String _id){
		DBObject query = new BasicDBObject();
		query.put("_id", new ObjectId(_id));
		DBObject task = this.findOne("rule", query);
		return task.get("rid").toString();
	}
	
	public void deleteRule(String id){
		String col="rule";
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("_id", new ObjectId(id));
		this.delete(col, query);
	}
	
	public List<DBObject> getRuleTree(String taskid){
		if(!StringUtils.hasLength(taskid))return null;
		List<DBObject> list = this.findList("rule",new BasicDBObject("taskid", taskid));
		System.out.println(list);
		return list;
	}

	public List<DBObject> ruletree(String taskid,String pid){
		DBObject query = new BasicDBObject();
		query.put("pid", pid);
		query.put("taskid", taskid);
		List<DBObject> task = this.findList("rule", query);
		return task;
	}

	public void delRulesByTid(String tid){
		this.delete("rule",new BasicDBObject("taskid",tid));
	}
	
	public List<DBObject> findRule(String taskid){
		String col="rule";
		DBObject query = new BasicDBObject();
		query.put("taskid", taskid);
		List<DBObject> ruleList = this.findList(col, query);
		return ruleList;
	}
	
	public void copyRule(DBObject rule,String taskid){
		rule.removeField("_id");
		rule.put("taskid", taskid);
		this.insert("rule", rule);
	}
	
	
}
